home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / mint / utilit~1 / futilsrc.zoo / fileutil / src / cp.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-19  |  28.6 KB  |  1,209 lines

  1. /* cp.c  -- file copying (main routines)
  2.    Copyright (C) 1989-1991 Free Software Foundation.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.    Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. */
  19.  
  20. #ifdef _AIX
  21.  #pragma alloca
  22. #endif
  23. #include <stdio.h>
  24. #include <getopt.h>
  25. #include "cp.h"
  26. #include "backupfile.h"
  27.  
  28. /* Used by do_copy, make_path, and re_protect
  29.    to keep a list of leading directories whose protections
  30.    need to be fixed after copying. */
  31. struct dir_attr
  32. {
  33.   int is_new_dir;
  34.   int slash_offset;
  35.   struct dir_attr *next;
  36. };
  37.  
  38. char *dirname ();
  39. enum backup_type get_version ();
  40. int eaccess_stat ();
  41.  
  42. static int make_path ();
  43. static int re_protect ();
  44.  
  45. /* Initial number of entries in each hash table entry's table of inodes.  */
  46. #define INITIAL_HASH_MODULE 100
  47.  
  48. /* Initial number of entries in the inode hash table.  */
  49. #define INITIAL_ENTRY_TAB_SIZE 70
  50.  
  51. /* A pointer to either lstat or stat, depending on
  52.    whether dereferencing of symlinks is done.  */
  53. int (*xstat) ();
  54.  
  55. /* The invocation name of this program.  */
  56. char *program_name;
  57.  
  58. /* If nonzero, copy all files except directories and, if not dereferencing
  59.    them, symbolic links, as if they were regular files. */
  60. int flag_copy_as_regular = 1;
  61.  
  62. /* If nonzero, dereference symbolic links (copy the files they point to). */
  63. int flag_dereference = 1;
  64.  
  65. /* If nonzero, remove existing target nondirectories. */
  66. int flag_force = 0;
  67.  
  68. /* If nonzero, create hard links instead of copying files.
  69.    Create target directories as usual. */
  70. int flag_hard_link = 0;
  71.  
  72. /* If nonzero, query before overwriting existing targets with regular files. */
  73. int flag_interactive = 0;
  74.  
  75. /* If nonzero, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
  76.    as its target instead of the usual "e_dir/e_file." */
  77. int flag_path = 0;
  78.  
  79. /* If nonzero, give the copies the original files' permissions,
  80.    ownership, and timestamps. */
  81. int flag_preserve = 0;
  82.  
  83. /* If nonzero, copy directories recursively and copy special files
  84.    as themselves rather than copying their contents. */
  85. int flag_recursive = 0;
  86.  
  87. /* If nonzero, create symbolic links instead of copying files.
  88.    Create target directories as usual. */
  89. int flag_symbolic_link = 0;
  90.  
  91. /* If nonzero, when copying recursively, skip any subdirectories that are
  92.    on different filesystems from the one we started on. */
  93. int flag_one_file_system = 0;
  94.  
  95. /* If nonzero, do not copy a nondirectory that has an existing destination
  96.    with the same or newer modification time. */
  97. int flag_update = 0;
  98.  
  99. /* If nonzero, display the names of the files before copying them. */
  100. int flag_verbose = 0;
  101.  
  102. /* The error code to return to the system. */
  103. int exit_status = 0;
  104.  
  105. /* The bits to preserve in created files' modes. */
  106. int umask_kill;
  107.  
  108. struct option long_opts[] =
  109. {
  110.   {"archive", 0, NULL, 'a'},
  111.   {"backup", 0, NULL, 'b'},
  112.   {"force", 0, NULL, 'f'},
  113.   {"interactive", 0, NULL, 'i'},
  114.   {"link", 0, NULL, 'l'},
  115.   {"no-dereference", 0, &flag_dereference, 0},
  116.   {"one-file-system", 0, &flag_one_file_system, 1},
  117.   {"path", 0, &flag_path, 1},
  118.   {"preserve", 0, &flag_preserve, 1},
  119.   {"recursive", 0, NULL, 'R'},
  120.   {"suffix", 1, NULL, 'S'},
  121.   {"symbolic-link", 0, NULL, 's'},
  122.   {"update", 0, &flag_update, 1},
  123.   {"verbose", 0, &flag_verbose, 1},
  124.   {"version-control", 1, NULL, 'V'},
  125.   {NULL, 0, NULL, 0}
  126. };
  127.  
  128. void
  129. main (argc, argv)
  130.      int argc;
  131.      char *argv[];
  132. {
  133.   int c;
  134.   int make_backups = 0;
  135.   char *version;
  136.  
  137.   program_name = argv[0];
  138.  
  139.   version = getenv ("SIMPLE_BACKUP_SUFFIX");
  140.   if (version)
  141.     simple_backup_suffix = version;
  142.   version = getenv ("VERSION_CONTROL");
  143.  
  144.   /* Find out the current file creation mask, to knock the right bits
  145.      when using chmod.  The creation mask is set to to be liberal, so
  146.      that created directories can be written, even if it would not
  147.      have been allowed with the mask this process was started with.  */
  148.  
  149.   umask_kill = 0777777 ^ umask (0);
  150.  
  151.   while ((c = getopt_long (argc, argv, "abdfilprsuvxPRS:V:", long_opts,
  152.                (int *) 0)) != EOF)
  153.     {
  154.       switch (c)
  155.     {
  156.     case 0:
  157.       break;
  158.  
  159.     case 'a':        /* Like -dpR. */
  160.       flag_dereference = 0;
  161.       flag_preserve = 1;
  162.       flag_recursive = 1;
  163.       flag_copy_as_regular = 0;
  164.       break;
  165.  
  166.     case 'b':
  167.       make_backups = 1;
  168.       break;
  169.  
  170.     case 'd':
  171.       flag_dereference = 0;
  172.       break;
  173.  
  174.     case 'f':
  175.       flag_force = 1;
  176.       flag_interactive = 0;
  177.       break;
  178.  
  179.     case 'i':
  180.       flag_force = 0;
  181.       flag_interactive = 1;
  182.       break;
  183.  
  184.     case 'l':
  185.       flag_hard_link = 1;
  186.       break;
  187.  
  188.     case 'p':
  189.       flag_preserve = 1;
  190.       break;
  191.  
  192.     case 'P':
  193.       flag_path = 1;
  194.       break;
  195.  
  196.     case 'r':
  197.       flag_recursive = 1;
  198.       flag_copy_as_regular = 1;
  199.       break;
  200.  
  201.     case 'R':
  202.       flag_recursive = 1;
  203.       flag_copy_as_regular = 0;
  204.       break;
  205.  
  206.     case 's':
  207. #ifdef S_ISLNK
  208.       flag_symbolic_link = 1;
  209. #else
  210.       error (0, 0, "symbolic links not supported; making hard links");
  211.       flag_hard_link = 1;
  212. #endif
  213.       break;
  214.  
  215.     case 'u':
  216.       flag_update = 1;
  217.       break;
  218.  
  219.     case 'v':
  220.       flag_verbose = 1;
  221.       break;
  222.  
  223.     case 'x':
  224.       flag_one_file_system = 1;
  225.       break;
  226.  
  227.     case 'S':
  228.       simple_backup_suffix = optarg;
  229.       break;
  230.  
  231.     case 'V':
  232.       version = optarg;
  233.       break;
  234.  
  235.     default:
  236.       usage ((char *) 0);
  237.     }
  238.     }
  239.  
  240.   if (flag_hard_link && flag_symbolic_link)
  241.     usage ("cannot make both hard and symbolic links");
  242.  
  243.   if (make_backups)
  244.     backup_type = get_version (version);
  245.  
  246.   if (flag_preserve == 1)
  247.     umask_kill = 0777777;
  248.  
  249.   /* The key difference between -d (+no-dereference) and not is the version
  250.      of `stat' to call.  */
  251.  
  252.   if (flag_dereference)
  253.     xstat = stat;
  254.   else
  255.     xstat = lstat;
  256.  
  257.   /* Allocate space for remembering copied and created files.  */
  258.  
  259.   hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
  260.  
  261.   exit_status |= do_copy (argc, argv);
  262.  
  263.   exit (exit_status);
  264. }
  265.  
  266. /* Scan the arguments, and copy each by calling copy.
  267.    Return 0 if successful, 1 if any errors occur. */
  268.  
  269. int
  270. do_copy (argc, argv)
  271.      int argc;
  272.      char *argv[];
  273. {
  274.   char *target;
  275.   struct stat sb;
  276.   int new_dst = 0;
  277.   int ret = 0;
  278.  
  279.   if (optind >= argc)
  280.     usage ("missing file arguments");
  281.   if (optind >= argc - 1)
  282.     usage ("missing file argument");
  283.  
  284.   target = argv[argc - 1];
  285.  
  286.   strip_trailing_slashes (target);
  287.  
  288.   if (lstat (target, &sb))
  289.     {
  290.       if (errno != ENOENT)
  291.     {
  292.       error (0, errno, "%s", target);
  293.       return 1;
  294.     }
  295.       else
  296.     new_dst = 1;
  297.     }
  298.   else
  299.     {
  300.       struct stat sbx;
  301.  
  302.       /* If `target' is not a symlink to a nonexistent file, use
  303.      the results of stat instead of lstat, so we can copy files
  304.      into symlinks to directories. */
  305.       if (stat (target, &sbx) == 0)
  306.     sb = sbx;
  307.     }
  308.  
  309.   if (!new_dst && S_ISDIR (sb.st_mode))
  310.     {
  311.       /* cp file1...filen edir
  312.      Copy the files `file1' through `filen'
  313.      to the existing directory `edir'. */
  314.  
  315.       for (;;)
  316.     {
  317.       char *arg;
  318.       char *ap;
  319.       char *dst_path;
  320.       int parent_exists = 1; /* True if dirname (dst_path) exists. */
  321.       struct dir_attr *attr_list;
  322.  
  323.       arg = argv[optind];
  324.  
  325.       strip_trailing_slashes (arg);
  326.  
  327.       if (flag_path)
  328.         {
  329.           /* Append all of `arg' to `target'.  */
  330.           dst_path = xmalloc (strlen (target) + strlen (arg) + 2);
  331.           stpcpy (stpcpy (stpcpy (dst_path, target), "/"), arg);
  332.  
  333.           /* For +path, we have to make sure that the directory
  334.              dirname (dst_path) exists.  We may have to create a few
  335.              leading directories. */
  336.           parent_exists = !make_path (dst_path,
  337.                       strlen (target) + 1, 0700,
  338.                       flag_verbose ? "%s -> %s\n" :
  339.                       (char *) NULL,
  340.                       &attr_list, &new_dst);
  341.         }
  342.         else
  343.           {
  344.           /* Append the last component of `arg' to `target'.  */
  345.  
  346.           ap = basename (arg);
  347.           /* For `cp -R source/.. target', don't copy into `target/..'. */
  348.           if (!strcmp (ap, ".."))
  349.         dst_path = target;
  350.           else
  351.         {
  352.           dst_path = xmalloc (strlen (target) + strlen (ap) + 2);
  353.           stpcpy (stpcpy (stpcpy (dst_path, target), "/"), ap);
  354.         }
  355.         }
  356.  
  357.       if (!parent_exists)
  358.         {
  359.           /* make_path failed, so we shouldn't even attempt the copy. */
  360.           ret = 1;
  361.           }
  362.       else
  363.         {
  364.           ret |= copy (arg, dst_path, new_dst, 0, (struct dir_list *) 0);
  365.           forget_all ();
  366.   
  367.           if (flag_path)
  368.         {
  369.           ret |= re_protect (dst_path, strlen (target) + 1,
  370.                     attr_list);
  371.         }
  372.         }
  373.  
  374.       ++optind;
  375.       if (optind == argc - 1)
  376.         break;
  377.     }
  378.       return ret;
  379.     }
  380.   else if (argc - optind == 2)
  381.     {
  382.       if (flag_path)
  383.     usage ("when preserving paths, last argument must be a directory");
  384.       return copy (argv[optind], target, new_dst, 0, (struct dir_list *) 0);
  385.     }
  386.   else
  387.     usage ("when copying multiple files, last argument must be a directory");
  388. }
  389.  
  390. /* Copy the file SRC_PATH to the file DST_PATH.  The files may be of
  391.    any type.  NEW_DST should be non-zero if the file DST_PATH cannot
  392.    exist because its parent directory was just created; NEW_DST should
  393.    be zero if DST_PATH might already exist.  DEVICE is the device
  394.    number of the parent directory, or 0 if the parent of this file is
  395.    not known.  ANCESTORS points to a linked, null terminated list of
  396.    devices and inodes of parent directories of SRC_PATH.
  397.    Return 0 if successful, 1 if an error occurs. */
  398.  
  399. int
  400. copy (src_path, dst_path, new_dst, device, ancestors)
  401.      char *src_path;
  402.      char *dst_path;
  403.      int new_dst;
  404.      dev_t device;
  405.      struct dir_list *ancestors;
  406. {
  407.   struct stat src_sb;
  408.   struct stat dst_sb;
  409.   int src_mode;
  410.   int src_type;
  411.   char *earlier_file;
  412.   char *dst_backup = NULL;
  413.   int dir_mode_changed = 0;
  414.  
  415.   if ((*xstat) (src_path, &src_sb))
  416.     {
  417.       error (0, errno, "%s", src_path);
  418.       return 1;
  419.     }
  420.  
  421.   /* Are we crossing a file system boundary?  */
  422.   if (flag_one_file_system && device != 0 && device != src_sb.st_dev)
  423.     return 0;
  424.  
  425.   /* We wouldn't insert a node unless nlink > 1, except that we need to
  426.      find created files so as to not copy infinitely if a directory is
  427.      copied into itself.  */
  428.  
  429.   earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
  430.  
  431.   /* Did we just create this file?  */
  432.  
  433.   if (earlier_file == &new_file)
  434.     return 0;
  435.  
  436.   src_mode = src_sb.st_mode;
  437.   src_type = src_sb.st_mode;
  438.  
  439.   if (S_ISDIR (src_type) && !flag_recursive)
  440.     {
  441.       error (0, 0, "%s: omitting directory", src_path);
  442.       return 1;
  443.     }
  444.  
  445.   if (!new_dst)
  446.     {
  447.       if ((*xstat) (dst_path, &dst_sb))
  448.     {
  449.       if (errno != ENOENT)
  450.         {
  451.           error (0, errno, "%s", dst_path);
  452.           return 1;
  453.         }
  454.       else
  455.         new_dst = 1;
  456.     }
  457.       else
  458.     {
  459.       /* The file exists already.  */
  460.  
  461.       if (src_sb.st_ino == dst_sb.st_ino && src_sb.st_dev == dst_sb.st_dev)
  462.         {
  463.           if (flag_hard_link)
  464.         return 0;
  465.  
  466.           error (0, 0, "`%s' and `%s' are the same file",
  467.              src_path, dst_path);
  468.           return 1;
  469.         }
  470.  
  471.       if (!S_ISDIR (src_type))
  472.         {
  473.           if (S_ISDIR (dst_sb.st_mode))
  474.         {
  475.           error (0, 0,
  476.              "%s: cannot overwrite directory with non-directory",
  477.              dst_path);
  478.           return 1;
  479.         }
  480.  
  481.           if (flag_update && src_sb.st_mtime <= dst_sb.st_mtime)
  482.         return 0;
  483.         }
  484.  
  485.       if (S_ISREG (src_type) && !flag_force)
  486.         {
  487.           if (flag_interactive)
  488.         {
  489.           if (eaccess_stat (&dst_sb, W_OK) != 0)
  490.             fprintf (stderr,
  491.                  "%s: overwrite `%s', overriding mode %04o? ",
  492.                  program_name, dst_path, dst_sb.st_mode & 07777);
  493.           else
  494.             fprintf (stderr, "%s: overwrite `%s'? ",
  495.                  program_name, dst_path);
  496.           if (!yesno ())
  497.             return 0;
  498.         }
  499.         }
  500.  
  501.       if (backup_type != none && !S_ISDIR (dst_sb.st_mode))
  502.         {
  503.           char *tmp_backup = find_backup_file_name (dst_path);
  504.           if (tmp_backup == NULL)
  505.         error (1, 0, "virtual memory exhausted");
  506.           dst_backup = alloca (strlen (tmp_backup) + 1);
  507.           strcpy (dst_backup, tmp_backup);
  508.           free (tmp_backup);
  509.           if (rename (dst_path, dst_backup))
  510.         {
  511.           if (errno != ENOENT)
  512.             {
  513.               error (0, errno, "cannot backup `%s'", dst_path);
  514.               return 1;
  515.             }
  516.           else
  517.             dst_backup = NULL;
  518.         }
  519.           new_dst = 1;
  520.         }
  521.       else if (flag_force)
  522.         {
  523.           if (S_ISDIR (dst_sb.st_mode))
  524.         {
  525.           /* Temporarily change mode to allow overwriting. */
  526.           if (eaccess_stat (&dst_sb, W_OK | X_OK) != 0)
  527.             {
  528.               if (chmod (dst_path, 0700))
  529.             {
  530.               error (0, errno, "%s", dst_path);
  531.               return 1;
  532.             }
  533.               else
  534.             dir_mode_changed = 1;
  535.             }
  536.         }
  537.           else
  538.         {
  539.           if (unlink (dst_path) && errno != ENOENT)
  540.             {
  541.               error (0, errno, "cannot remove old link to `%s'",
  542.                  dst_path);
  543.               return 1;
  544.             }
  545.           new_dst = 1;
  546.         }
  547.         }
  548.     }
  549.     }
  550.  
  551.   /* If the source is a directory, we don't always create the target
  552.      directory.  So +verbose should not announce anything until we're
  553.      sure we'll create a directory. */
  554.   if (flag_verbose && !S_ISDIR (src_type))
  555.     printf ("%s -> %s\n", src_path, dst_path);
  556.  
  557.   /* Did we copy this inode somewhere else (in this command line argument)
  558.      and therefore this is a second hard link to the inode?  */
  559.  
  560.   if (!flag_dereference && src_sb.st_nlink > 1 && earlier_file)
  561.     {
  562.       if (link (earlier_file, dst_path))
  563.     {
  564.       error (0, errno, "%s", dst_path);
  565.       goto un_backup;
  566.     }
  567.       return 0;
  568.     }
  569.  
  570.   if (S_ISDIR (src_type))
  571.     {
  572.       struct dir_list *dir;
  573.  
  574.       /* If this directory has been copied before during the
  575.          recursion, there is a symbolic link to an ancestor
  576.          directory of the symbolic link.  It is impossible to
  577.          continue to copy this, unless we've got an infinite disk.  */
  578.  
  579.       if (is_ancestor (&src_sb, ancestors))
  580.     {
  581.       error (0, 0, "%s: cannot copy cyclic symbolic link", src_path);
  582.       goto un_backup;
  583.     }
  584.  
  585.       /* Insert the current directory in the list of parents.  */
  586.  
  587.       dir = (struct dir_list *) alloca (sizeof (struct dir_list));
  588.       dir->parent = ancestors;
  589.       dir->ino = src_sb.st_ino;
  590.       dir->dev = src_sb.st_dev;
  591.  
  592.       if (new_dst || !S_ISDIR (dst_sb.st_mode))
  593.     {
  594.       /* Create the new directory writable and searchable, so
  595.              we can create new entries in it.  */
  596.  
  597.       if (mkdir (dst_path, (src_mode & umask_kill) | 0700))
  598.         {
  599.           error (0, errno, "cannot create directory `%s'", dst_path);
  600.           goto un_backup;
  601.         }
  602.  
  603.       /* Insert the created directory's inode and device
  604.              numbers into the search structure, so that we can
  605.              avoid copying it again.  */
  606.  
  607.       if (remember_created (dst_path))
  608.         goto un_backup;
  609.  
  610.       if (flag_verbose)
  611.         printf ("%s -> %s\n", src_path, dst_path);
  612.     }
  613.  
  614.       /* Copy the contents of the directory.  */
  615.  
  616.       if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir))
  617.     return 1;
  618.     }
  619. #ifdef S_ISLNK
  620.   else if (flag_symbolic_link)
  621.     {
  622.       if (*src_path == '/'
  623.       || (!strncmp (dst_path, "./", 2) && index (dst_path + 2, '/') == 0)
  624.       || index (dst_path, '/') == 0)
  625.     {
  626.       if (symlink (src_path, dst_path))
  627.         {
  628.           error (0, errno, "%s", dst_path);
  629.           goto un_backup;
  630.         }
  631.       return 0;
  632.     }
  633.       else
  634.     {
  635.       error (0, 0,
  636.          "%s: can only make relative symbolic links in current directory", dst_path);
  637.       goto un_backup;
  638.     }
  639.     }
  640. #endif
  641.   else if (flag_hard_link)
  642.     {
  643.       if (link (src_path, dst_path))
  644.     {
  645.       error (0, errno, "cannot create link `%s'", dst_path);
  646.       goto un_backup;
  647.     }
  648.       return 0;
  649.     }
  650.   else if (S_ISREG (src_type)
  651.        || (flag_copy_as_regular && !S_ISDIR (src_type)
  652. #ifdef S_ISLNK
  653.            && !S_ISLNK (src_type)
  654. #endif
  655.            ))
  656.     {
  657.       if (copy_reg (src_path, dst_path))
  658.     goto un_backup;
  659.     }
  660.   else
  661. #ifdef S_ISFIFO
  662.   if (S_ISFIFO (src_type))
  663.     {
  664.       if (mkfifo (dst_path, src_mode & umask_kill))
  665.     {
  666.       error (0, errno, "cannot create fifo `%s'", dst_path);
  667.       goto un_backup;
  668.     }
  669.     }
  670.   else
  671. #endif
  672.     if (S_ISBLK (src_type) || S_ISCHR (src_type)
  673. #ifdef S_ISSOCK
  674.     || S_ISSOCK (src_type)
  675. #endif
  676.     )
  677.     {
  678.       if (mknod (dst_path, src_mode & umask_kill, src_sb.st_rdev))
  679.     {
  680.       error (0, errno, "cannot create special file `%s'", dst_path);
  681.       goto un_backup;
  682.     }
  683.     }
  684.   else
  685. #ifdef S_ISLNK
  686. #ifdef _AIX
  687. #define LINK_BUF PATH_MAX
  688. #else
  689. #define LINK_BUF src_sb.st_size
  690. #endif
  691.   if (S_ISLNK (src_type))
  692.     {
  693.       char *link_val = (char *) alloca (LINK_BUF + 1);
  694.       int link_size;
  695.  
  696.       link_size = readlink (src_path, link_val, LINK_BUF);
  697.       if (link_size < 0)
  698.     {
  699.       error (0, errno, "cannot read symbolic link `%s'", src_path);
  700.       goto un_backup;
  701.     }
  702.       link_val[link_size] = '\0';
  703.  
  704.       if (symlink (link_val, dst_path))
  705.     {
  706.       error (0, errno, "cannot create symbolic link `%s'", dst_path);
  707.       goto un_backup;
  708.     }
  709.       return 0;
  710.     }
  711.   else
  712. #endif
  713.     {
  714.       error (0, 0, "%s: unknown file type", src_path);
  715.       goto un_backup;
  716.     }
  717.  
  718.   if ((flag_preserve || new_dst)
  719.       && (S_ISREG (src_type) || S_ISDIR (src_type)))
  720.     {
  721.       if (chmod (dst_path, src_mode & umask_kill))
  722.     {
  723.       error (0, errno, "%s", dst_path);
  724.       return 1;
  725.     }
  726.     }
  727.   else if (dir_mode_changed)
  728.     {
  729.       /* Reset the temporarily changed mode.  */
  730.       if (chmod (dst_path, dst_sb.st_mode))
  731.     {
  732.       error (0, errno, "%s", dst_path);
  733.       return 1;
  734.     }
  735.     }
  736.  
  737.   /* Adjust the times (and if possible, ownership) for the copy. */
  738.  
  739.   if (flag_preserve)
  740.     {
  741.       struct utimbuf utb;
  742.  
  743.       utb.actime = src_sb.st_atime;
  744.       utb.modtime = src_sb.st_mtime;
  745.  
  746.       if (utime (dst_path, &utb))
  747.     {
  748.       error (0, errno, "%s", dst_path);
  749.       return 1;
  750.     }
  751.  
  752.       if (chown (dst_path, src_sb.st_uid, src_sb.st_gid) && errno != EPERM)
  753.     {
  754.       error (0, errno, "%s", dst_path);
  755.       return 1;
  756.     }
  757.     }
  758.  
  759.   return 0;
  760.  
  761. un_backup:
  762.   if (dst_backup)
  763.     {
  764.       if (rename (dst_backup, dst_path))
  765.     error (0, errno, "cannot un-backup `%s'", dst_path);
  766.     }
  767.   return 1;
  768. }
  769.  
  770. /* Ensure that the parent directory of CONST_DIRPATH exists, for
  771.    the +path option.
  772.  
  773.    SRC_OFFSET is the index in CONST_DIRPATH (which is a destination
  774.    path) of the beginning of the source directory name.
  775.    Create any leading directories that don't already exist,
  776.    giving them permissions MODE.
  777.    If VERBOSE_FMT_STRING is nonzero, use it as a printf format
  778.    string for printing a message after successfully making a directory.
  779.    The format should take two string arguments: the names of the
  780.    source and destination directories.
  781.    Creates a linked list of attributes of intermediate directories,
  782.    *ATTR_LIST, for re_protect to use after calling copy.
  783.    Sets *NEW_DST to 1 if this function creates parent of CONST_DIRPATH.
  784.  
  785.    Return 0 if parent of CONST_DIRPATH exists as a directory with the proper
  786.    permissions when done, otherwise 1. */
  787.  
  788. static int
  789. make_path (const_dirpath, src_offset, mode, verbose_fmt_string,
  790.           attr_list, new_dst)
  791.      char *const_dirpath;
  792.      int src_offset;
  793.      int mode;
  794.      char *verbose_fmt_string;
  795.      struct dir_attr **attr_list;
  796.      int *new_dst;
  797. {
  798.   struct stat stats;
  799.   char *dirpath;        /* A copy of CONST_DIRPATH we can change. */
  800.   char *src;            /* Source name in `dirpath'. */
  801.   char *tmp_dst_dirname;    /* Leading path of `dirpath', malloc. */
  802.   char *dst_dirname;        /* Leading path of `dirpath', alloca. */
  803.  
  804.   dirpath = alloca (strlen (const_dirpath));
  805.   strcpy (dirpath, const_dirpath);
  806.  
  807.   src = dirpath + src_offset;
  808.  
  809.   tmp_dst_dirname = dirname (dirpath); 
  810.   dst_dirname = alloca (strlen (tmp_dst_dirname));
  811.   strcpy (dst_dirname, tmp_dst_dirname);
  812.   free (tmp_dst_dirname);
  813.  
  814.   *attr_list = NULL;
  815.  
  816.   if ((*xstat) (dst_dirname, &stats))
  817.     {
  818.       /* Parent of CONST_DIRNAME does not exist.
  819.      Make all missing intermediate directories. */
  820.       char *slash;
  821.  
  822.       slash = src;
  823.       while (*slash == '/')
  824.     slash++;
  825.       while (slash = index (slash, '/'))
  826.     {
  827.       /* Add this directory to the list of directories whose modes need
  828.          fixing later. */
  829.       struct dir_attr *new =
  830.         (struct dir_attr *) xmalloc (sizeof (struct dir_attr));
  831.       new->slash_offset = slash - dirpath;
  832.       new->next = *attr_list;
  833.       *attr_list = new;
  834.  
  835.       *slash = '\0';
  836.       if ((*xstat) (dirpath, &stats))
  837.         {
  838.           /* This element of the path does not exist.  We must set
  839.          *new_dst and new->is_new_dir inside this loop because,
  840.          for example, in the command `cp +path ../a/../b/c e_dir',
  841.          make_path creates only e_dir/../a if ./b already exists. */
  842.           *new_dst = 1;
  843.           new->is_new_dir = 1;
  844.           if (mkdir (dirpath, mode))
  845.         {
  846.           error (0, errno, "cannot make directory `%s'", dirpath);
  847.           return 1;
  848.         }
  849.           else
  850.         {
  851.           if (verbose_fmt_string != NULL)
  852.             printf (verbose_fmt_string, src, dirpath);
  853.         }
  854.         }
  855.       else if (!S_ISDIR (stats.st_mode))
  856.         {
  857.           error (0, 0, "`%s' exists but is not a directory", dirpath);
  858.           return 1;
  859.         }
  860.       else
  861.         {
  862.           new->is_new_dir = 0;
  863.           *new_dst = 0;
  864.         }
  865.       *slash++ = '/';
  866.  
  867.       /* Avoid unnecessary calls to `stat' when given
  868.          pathnames containing multiple adjacent slashes.  */
  869.       while (*slash == '/')
  870.         slash++;
  871.     }
  872.     }
  873.  
  874.   /* We get here if the parent of `dirpath' already exists. */
  875.  
  876.   else if (!S_ISDIR (stats.st_mode))
  877.     {
  878.       error (0, 0, "`%s' exists but is not a directory", dst_dirname);
  879.       return 1;
  880.     }
  881.   else if (chmod (dst_dirname, mode))
  882.     {
  883.       error (0, errno, "%s", dst_dirname);
  884.       return 1;
  885.     }
  886.   else
  887.     {
  888.       *new_dst = 0;
  889.     }
  890.   return 0;
  891. }
  892.  
  893. /* Ensure that the parent directories of CONST_DST_PATH have the
  894.    correct protections, for the +path option.  This is done
  895.    after all copying has been completed, to allow permissions
  896.    that don't include user write/execute.
  897.  
  898.    SRC_OFFSET is the index in CONST_DST_PATH of the beginning of the
  899.    source directory name.
  900.  
  901.    ATTR_LIST is a null-terminated linked list of structures that
  902.    indicates the end of the filename of each intermediate directory
  903.    in CONST_DST_PATH that may need to have its attributes changed.
  904.    The command `cp +path +preserve a/b/c d/e_dir' changes the
  905.    attributes of the directories d/e_dir/a and d/e_dir/a/b to match
  906.    the corresponding source directories regardless of whether they
  907.    existed before the `cp' command was given.
  908.  
  909.    Return 0 if the parent of CONST_DST_PATH and any intermediate
  910.    directories specified by ATTR_LIST have the proper permissions
  911.    when done, otherwise 1. */
  912.  
  913. static int
  914. re_protect (const_dst_path, src_offset, attr_list)
  915.      char *const_dst_path;
  916.      int src_offset;
  917.      struct dir_attr *attr_list;
  918. {
  919.   struct dir_attr *p;
  920.   char *dst_path;        /* A copy of CONST_DST_PATH we can change. */
  921.   char *src_path;        /* The source name in `dst_path'. */
  922.  
  923.   dst_path = alloca (strlen (const_dst_path));
  924.   strcpy (dst_path, const_dst_path);
  925.   src_path = dst_path + src_offset; 
  926.  
  927.   for (p = attr_list; p; p = p->next)
  928.     {
  929.       struct stat src_sb;
  930.  
  931.       dst_path[p->slash_offset] = '\0';
  932.  
  933.       if ((*xstat) (src_path, &src_sb))
  934.     {
  935.       error (0, errno, "%s", src_path);
  936.       return 1;
  937.     }
  938.  
  939.       if (flag_preserve || p->is_new_dir)
  940.     {
  941.       if (chmod (dst_path, src_sb.st_mode & umask_kill))
  942.         {
  943.           error (0, errno, "%s", dst_path);
  944.           return 1;
  945.         }
  946.     }
  947.  
  948.       /* Adjust the times (and if possible, ownership) for the copy. */
  949.  
  950.       if (flag_preserve)
  951.     {
  952.       struct utimbuf utb;
  953.  
  954.       utb.actime = src_sb.st_atime;
  955.       utb.modtime = src_sb.st_mtime;
  956.  
  957.       if (utime (dst_path, &utb))
  958.         {
  959.           error (0, errno, "%s", dst_path);
  960.           return 1;
  961.         }
  962.  
  963.       if (chown (dst_path, src_sb.st_uid, src_sb.st_gid) && errno != EPERM)
  964.         {
  965.           error (0, errno, "%s", dst_path);
  966.           return 1;
  967.         }
  968.     }
  969.  
  970.       dst_path[p->slash_offset] = '/';
  971.     }
  972.   return 0;
  973. }
  974.  
  975. /* Read the contents of the directory SRC_PATH_IN, and recursively
  976.    copy the contents to DST_PATH_IN.  NEW_DST is non-zero if
  977.    DST_PATH_IN is a directory that was created previously in the
  978.    recursion.   SRC_SB and ANCESTORS describe SRC_PATH_IN.
  979.    Return 0 if successful, -1 if an error occurs. */
  980.  
  981. int
  982. copy_dir (src_path_in, dst_path_in, new_dst, src_sb, ancestors)
  983.      char *src_path_in;
  984.      char *dst_path_in;
  985.      int new_dst;
  986.      struct stat *src_sb;
  987.      struct dir_list *ancestors;
  988. {
  989.   char *name_space;
  990.   char *namep;
  991.   char *src_path;
  992.   char *dst_path;
  993.   int ret = 0;
  994.  
  995.   errno = 0;
  996.   name_space = savedir (src_path_in, src_sb->st_size);
  997.   if (name_space == 0)
  998.     {
  999.       if (errno)
  1000.     {
  1001.       error (0, errno, "%s", src_path_in);
  1002.       return -1;
  1003.     }
  1004.       else
  1005.     error (1, 0, "virtual memory exhausted");
  1006.     }
  1007.  
  1008.   namep = name_space;
  1009.   while (*namep != '\0')
  1010.     {
  1011.       int fn_length = strlen (namep) + 1;
  1012.  
  1013.       dst_path = xmalloc (strlen (dst_path_in) + fn_length + 1);
  1014.       src_path = xmalloc (strlen (src_path_in) + fn_length + 1);
  1015.  
  1016.       stpcpy (stpcpy (stpcpy (src_path, src_path_in), "/"), namep);
  1017.       stpcpy (stpcpy (stpcpy (dst_path, dst_path_in), "/"), namep);
  1018.  
  1019.       ret |= copy (src_path, dst_path, new_dst, src_sb->st_dev, ancestors);
  1020.  
  1021.       /* Free the memory for `src_path'.  The memory for `dst_path'
  1022.      cannot be deallocated, since it is used to create multiple
  1023.      hard links.  */
  1024.  
  1025.       free (src_path);
  1026.  
  1027.       namep += fn_length;
  1028.     }
  1029.   free (name_space);
  1030.   return -ret;
  1031. }
  1032.  
  1033. /* Copy a regular file from SRC_PATH to DST_PATH.  Large blocks of zeroes,
  1034.    as well as holes in the source file, are made into holes in the
  1035.    target file.  (Holes are read as zeroes by the `read' system call.)
  1036.    Return 0 if successful, -1 if an error occurred. */
  1037.  
  1038. int
  1039. copy_reg (src_path, dst_path)
  1040.      char *src_path;
  1041.      char *dst_path;
  1042. {
  1043.   char *buf;
  1044.   int buf_size;
  1045.   int target_desc;
  1046.   int source_desc;
  1047.   int n_read;
  1048.   int n_written;
  1049.   struct stat sb;
  1050.   char *cp;
  1051.   int *ip;
  1052.   int return_val = 0;
  1053.   long n_read_total = 0;
  1054.   int last_write_made_hole = 0;
  1055.   int make_holes = 0;
  1056.  
  1057.   source_desc = open (src_path, O_RDONLY);
  1058.   if (source_desc < 0)
  1059.     {
  1060.       error (0, errno, "%s", src_path);
  1061.       return -1;
  1062.     }
  1063.  
  1064.   /* Create the new regular file with small permissions initially,
  1065.      to not create a security hole.  */
  1066.  
  1067.   target_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
  1068.   if (target_desc < 0)
  1069.     {
  1070.       error (0, errno, "cannot create regular file `%s'", dst_path);
  1071.       return_val = -1;
  1072.       goto ret2;
  1073.     }
  1074.  
  1075.   /* Find out the optimal buffer size.  */
  1076.  
  1077.   if (fstat (target_desc, &sb))
  1078.     {
  1079.       error (0, errno, "%s", dst_path);
  1080.       return_val = -1;
  1081.       goto ret;
  1082.     }
  1083.  
  1084.   buf_size = ST_BLKSIZE (sb);
  1085.  
  1086. #ifndef ST_BLOCKS_MISSING
  1087.   if (S_ISREG (sb.st_mode))
  1088.     {
  1089.       /* Find out whether the file contains any sparse blocks. */
  1090.  
  1091.       if (fstat (source_desc, &sb))
  1092.     {
  1093.       error (0, errno, "%s", src_path);
  1094.       return_val = -1;
  1095.       goto ret;
  1096.     }
  1097.  
  1098.       /* If the file has fewer blocks than would normally
  1099.      be needed for a file of its size, then
  1100.      at least one of the blocks in the file is a hole. */
  1101.       if (S_ISREG (sb.st_mode) &&
  1102.       sb.st_size - (sb.st_blocks * DEV_BSIZE) >= DEV_BSIZE)
  1103.     make_holes = 1;
  1104.     }
  1105. #endif
  1106.  
  1107.   /* Make a buffer with space for a sentinel at the end.  */
  1108.  
  1109.   buf = (char *) alloca (buf_size + sizeof (int));
  1110.  
  1111.   for (;;)
  1112.     {
  1113.       n_read = read (source_desc, buf, buf_size);
  1114.       if (n_read < 0)
  1115.     {
  1116.       error (0, errno, "%s", src_path);
  1117.       return_val = -1;
  1118.       goto ret;
  1119.     }
  1120.       if (n_read == 0)
  1121.     break;
  1122.  
  1123.       n_read_total += n_read;
  1124.  
  1125.       ip = 0;
  1126.       if (make_holes)
  1127.     {
  1128.       buf[n_read] = 1;    /* Sentinel to stop loop.  */
  1129.  
  1130.       /* Find first non-zero *word*, or the word with the sentinel.  */
  1131.  
  1132.       ip = (int *) buf;
  1133.       while (*ip++ == 0)
  1134.         ;
  1135.  
  1136.       /* Find the first non-zero *byte*, or the sentinel.  */
  1137.  
  1138.       cp = (char *) (ip - 1);
  1139.       while (*cp++ == 0)
  1140.         ;
  1141.  
  1142.       /* If we found the sentinel, the whole input block was zero,
  1143.          and we can make a hole.  */
  1144.  
  1145.       if (cp > buf + n_read)
  1146.         {
  1147.           /* Make a hole.  */
  1148.           if (lseek (target_desc, (off_t) n_read, SEEK_CUR) < 0L)
  1149.         {
  1150.           error (0, errno, "%s", dst_path);
  1151.           return_val = -1;
  1152.           goto ret;
  1153.         }
  1154.           last_write_made_hole = 1;
  1155.         }
  1156.       else
  1157.         /* Clear to indicate that a normal write is needed. */
  1158.         ip = 0;
  1159.     }
  1160.       if (ip == 0)
  1161.     {
  1162.       n_written = write (target_desc, buf, n_read);
  1163.       if (n_written < n_read)
  1164.         {
  1165.           error (0, errno, "%s", dst_path);
  1166.           return_val = -1;
  1167.           goto ret;
  1168.         }
  1169.       last_write_made_hole = 0;
  1170.     }
  1171.     }
  1172.  
  1173.   /* If the file ends with a `hole', something needs to be written at
  1174.      the end.  Otherwise the kernel would truncate the file at the end
  1175.      of the last write operation.  */
  1176.  
  1177.   if (last_write_made_hole)
  1178.     {
  1179. #ifndef FTRUNCATE_MISSING
  1180.       /* Write a null character and truncate it again.  */
  1181.       if (write (target_desc, "", 1) != 1
  1182.       || ftruncate (target_desc, n_read_total) < 0)
  1183. #else
  1184.       /* Seek backwards one character and write a null.  */
  1185.       if (lseek (target_desc, (off_t) -1, SEEK_CUR) < 0L
  1186.       || write (target_desc, "", 1) != 1)
  1187. #endif
  1188.     {
  1189.       error (0, errno, "%s", dst_path);
  1190.       return_val = -1;
  1191.     }
  1192.     }
  1193.  
  1194. ret:
  1195.   if (close (target_desc) < 0)
  1196.     {
  1197.       error (0, errno, "%s", dst_path);
  1198.       return_val = -1;
  1199.     }
  1200. ret2:
  1201.   if (close (source_desc) < 0)
  1202.     {
  1203.       error (0, errno, "%s", src_path);
  1204.       return_val = -1;
  1205.     }
  1206.  
  1207.   return return_val;
  1208. }
  1209.